package com.feilong.commons.core.io;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * 飞龙操作系统相关类,可以读取操作系统相关数据
 * 
 * @author 金鑫 2010-2-4 上午10:50:47
 */
public final class OSUtil{

	/**
	 * 判断当前操作系统是否是Windows系统.
	 * 
	 * @return true---是Windows操作系统
	 */
	public static boolean isWindowsOS(){
		boolean isWindowsOS = false;
		String osName = System.getProperty("os.name");
		if (osName.toLowerCase().indexOf("windows") > -1){
			isWindowsOS = true;
		}
		return isWindowsOS;
	}

	/**
	 * 获取本机IP地址(自动区分Windows还是Linux操作系统)
	 * 
	 * @return
	 */
	public static String getLocalIP(){
		String sIP = "";
		InetAddress inetAddress = null;
		// 如果是Windows操作系统
		if (isWindowsOS()){
			inetAddress = getInetAddressLocalHost();
		}
		// 如果是Linux操作系统
		else{
			boolean bFindIP = false;
			Enumeration<NetworkInterface> netInterfaces = null;
			try{
				netInterfaces = NetworkInterface.getNetworkInterfaces();
			}catch (SocketException e){
				e.printStackTrace();
			}
			if (null != netInterfaces){
				NetworkInterface networkInterface = null;
				Enumeration<InetAddress> ips;
				//*********************************
				while (netInterfaces.hasMoreElements()){
					if (bFindIP){
						break;
					}
					networkInterface = netInterfaces.nextElement();
					// ----------特定情况，可以考虑用ni.getName判断
					// 遍历所有ip
					ips = networkInterface.getInetAddresses();
					while (ips.hasMoreElements()){
						inetAddress = ips.nextElement();
						if (inetAddress.isSiteLocalAddress() && !inetAddress.isLoopbackAddress() // 127.开头的都是lookback地址
								&& inetAddress.getHostAddress().indexOf(":") == -1){
							bFindIP = true;
							break;
						}
					}
				}
			}
		}
		if (null != inetAddress){
			sIP = inetAddress.getHostAddress();
		}
		return sIP;
	}

	/**
	 * 获取本机,计算机名
	 * 
	 * @return
	 */
	public static String getLocalHostName(){
		return getInetAddressLocalHost().getHostName();
	}

	/**
	 * 获得本机 InetAddress
	 * 
	 * @return
	 */
	private static InetAddress getInetAddressLocalHost(){
		InetAddress inetAddress = null;
		try{
			inetAddress = InetAddress.getLocalHost();
		}catch (UnknownHostException e){
			e.printStackTrace();
		}
		return inetAddress;
	}
}